﻿using System;
using System.Collections.Generic;
using FL.DBModule;

namespace FL.Bussiness
{
    /// <summary>
    /// 作者：江怀玉
    /// 日期：2015-5-12
    /// 公司：福流网络
    /// 描述：业务处理基类,提供常用的操作方法
    /// 
    /// </summary>
    public class BaseBussnies<TEntity> where TEntity : BaseEntity
    {
        #region 默认实例
        public BaseBussnies<TEntity> instance;
        public BaseBussnies<TEntity> Instance
        {
            get
            {
                if (instance == null)
                {
                    return new BaseBussnies<TEntity>();
                }
                return instance;
            }
            set
            {
                instance = value;
            }
        }
        #endregion 

        /// <summary>
        /// 实体类
        /// </summary>
        public BaseEntity entity
        {
            get;
            set;
        }

        public BaseBussnies()
        {
            //entity = default(TEntity);
        }

        public BaseBussnies(TEntity entitys)
        {
            entity = entitys;
        }

        #region 数据保存
        /// <summary>
        /// 数据保存
        /// </summary>
        /// <returns></returns>
        public virtual bool Save()
        {
            return false;
        }

        /// <summary>
        /// 插入
        /// </summary>
        /// <param name="entity">实体对象</param>
        public virtual bool Insert(BaseEntity entity)
        {
            FL.SPL.Factory.DialectFactory DF = FL.SPL.Factory.Dialects.GetDialect(entity);
            return DF.Save();
        }

        /// <summary>
        /// 获取插入更新的Sql Command
        /// </summary>
        /// <param name="entity">实体类</param>
        /// <returns></returns>
        public virtual string GetSqlCommand(BaseEntity entity)
        {
            FL.SPL.Factory.DialectFactory DF = FL.SPL.Factory.Dialects.GetDialect(entity);
            return DF.GetSqlCommand();
        }

        ///// <summary>
        ///// 
        ///// </summary>
        ///// <returns></returns>
        //public string[] GetKey()
        //{
        //    return this.GetKey(this.entity.getTableName());
        //}

        //public string[] GetKey(string tableName)
        //{
        //    string[] str = new string[2];
        //    TableInfoStruc entity = this.GetEntityByCondition<TableInfoStruc>("TableName='" + tableName + "' and Substring(PKey,1,1)='Y'");
        //    if (entity != null)
        //    {
        //        str[0] = entity.ColName;
        //        str[1] = entity.CType;
        //    }
        //    return str;
        //}
       
        /// <summary>
        /// 新增实体数据
        /// </summary>
        /// <param name="entitys">实体</param>
        public virtual bool Insert()
        {
           return Insert(this.entity);
        }


        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="entity">实体对象</param>
        public virtual bool Update(BaseEntity entity)
        {
            FL.SPL.Factory.DialectFactory DF = FL.SPL.Factory.Dialects.GetDialect(entity);
            return DF.Update();
        }

        public virtual bool Update()
        {
            return Update(this.entity);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="entity">实体对象</param>
        public virtual bool Delete(BaseEntity entity)
        {
            FL.SPL.Factory.DialectFactory DF = FL.SPL.Factory.Dialects.GetDialect(entity);
            return DF.Delete();
        }

        public virtual bool Delete()
        {
            return Delete(this.entity);
        }



        /// <summary>
        /// 通过条件删除数据
        /// </summary>
        /// <param name="condition">要传入的Where后面条件</param>
        /// <returns></returns>
        public virtual bool Delete(string condition)
        {
            FL.SPL.Factory.DialectFactory DF = FL.SPL.Factory.Dialects.GetDialect(entity);
            return DF.Delete(condition);
        }
        #endregion

        #region 数据检验
        /// <summary>
        /// 数据检查[合法性检查，格式检查]
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public virtual string CheckData(BaseEntity entity)
        {
            return "";
        }

        public virtual string CheckData()
        {
            return CheckData(this.entity);
        }

        #endregion

        #region 数据获取方法
        /// <summary>
        /// 获取所有数据
        /// </summary>
        /// <returns></returns>
        public virtual IList<TEntity> GetList()
        {
            return null;
        }

        /// <summary>
        /// 通过ID获取实体
        /// </summary>
        /// <param name="id">记录ID</param>
        /// <returns>实体</returns>
        public virtual object GetEntityById(string id)
        {
            if (id == "" || id == null)
            {
                return null;
            }
            else
            {
                try
                {
                    FL.SPL.Factory.DialectFactory df = FL.SPL.Factory.Dialects.GetDialect(this.entity);
                    string _strSel = df.SelectCommand(id);
                    return GetEntityBySqlComm(_strSel);
                }
                catch
                {

                    return null;
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="id"></param>
        /// <returns></returns>
        public virtual TEntity GetEntityById<T>(int id)
        {
            T be = Activator.CreateInstance<T>();
            return GetEntityByCondition<T>((be as BaseEntity).GetTableKeyField() + "='" + id + "'");
        }

        public virtual TEntity GetEntityById<T>(Guid id)
        {
            T be = Activator.CreateInstance<T>();
            return GetEntityByCondition<T>((be as BaseEntity).GetTableKeyField() + "='" + id.ToString() + "'");
        }


        /// <summary>
        /// 通过条件获取实体
        /// </summary>
        /// <param name="Condition">条件</param>
        /// <returns>实体</returns>
        public virtual object GetEntityByCondition(string Condition)
        {
            FL.SPL.Factory.DialectFactory df = FL.SPL.Factory.Dialects.GetDialect(entity);
            return this.GetEntityBySqlComm(df.SelectAllCommand() + " where " + Condition);
        }
        
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="Condition"></param>
        /// <returns></returns>
        public virtual TEntity GetEntityByCondition<T>(string Condition)
        {
            FL.SPL.Factory.DialectFactory df = FL.SPL.Factory.DialectFactory.instance(this.entity);
            return this.GetEntityBySqlComm<TEntity>(df.SelectAllCommand() + " where " + Condition);
        }

        public virtual System.Data.DataTable GetDataTableByCondition(string Condition)
        {
            FL.SPL.Factory.DialectFactory df = FL.SPL.Factory.DialectFactory.instance(this.entity);
            return this.GetDataTableBySqlComm(df.SelectAllCommand() + " where " + Condition);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="Condition"></param>
        /// <returns></returns>
        public virtual IList<TEntity> GetEntityListByCondition<T>(string Condition)
        {
            Condition = String.IsNullOrEmpty(Condition) ? "1=1" : Condition;
            if (Condition == null || Condition == string.Empty)
            {
                return null;
            }
            else
            {
                FL.SPL.Factory.DialectFactory df = FL.SPL.Factory.DialectFactory.instance(this.entity);
                return this.GetEntitysBySqlComm<T>(df.SelectAllCommand() + " where " + Condition);
            }
        }

        /// <summary>
        /// 通过SqlComm命令获取实体
        /// </summary>
        /// <param name="SqlComm">Sql Command</param>
        /// <returns>实体</returns>
        public virtual object GetEntityBySqlComm(string SqlComm)
        {
            if (SqlComm == null || SqlComm == string.Empty)
            {
                return null;
            }
            else
            {
                try
                {
                    FL.SPL.ORM.ObjectMapper om = new FL.SPL.ORM.ObjectMapper(entity);
                    om.SqlComm = SqlComm;
                    return om.DataTableToObject();
                }
                catch
                {
                    return null;
                }
            }
        }


        public virtual System.Data.DataTable GetDataBySqlComm(string SqlComm)
        {
            if (SqlComm == null || SqlComm == string.Empty)
            {
                return null;
            }
            else
            {
                try
                {
                    FL.SPL.ORM.ObjectMapper om = new FL.SPL.ORM.ObjectMapper(entity);
                    om.SqlComm = SqlComm;
                    return om.GetDataBySqlComm();
                }
                catch
                {
                    return null;
                }
            }
        }

        /// <summary>
        /// 通过命令获取实体对象
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="SqlComm"></param>
        /// <returns></returns>
        public virtual TEntity GetEntityBySqlComm<T>(string SqlComm) where T : BaseEntity
        {
            if (SqlComm == null || SqlComm == string.Empty)
            {
                return default(T) as TEntity;
            }
            else
            {
                try
                {
                    FL.SPL.ORM.TObject<T> om = new FL.SPL.ORM.TObject<T>(SqlComm);
                    //om.SqlComm = SqlComm;
                    return om.DataTableToObject() as TEntity;
                }
                catch
                {
                    return default(T) as TEntity;
                }
            }
        }


        public virtual IList<TEntity> GetEntitysBySqlComm<T>(string SqlComm)
        {
            if (SqlComm == null || SqlComm == string.Empty)
            {
                return null;
            }
            else
            {
                try
                {
                    SqlComm = iTop > 0 ? SqlComm.ToLower().Replace("select", "select top " + iTop.ToString()) : SqlComm;
                    string order = this.Order == "" || this.Order == null ? "" : " Order by " + this.Order;
                    order = order == "" ? " " : order + (this.Desc == "Yes" ? " Desc " : " Asc");
                    FL.SPL.ORM.TObject<TEntity> om = new FL.SPL.ORM.TObject<TEntity>(SqlComm);
                    om.SqlComm = SqlComm + " " + order;
                    return om.DatatableToObject<TEntity>();
                }
                catch (System.Exception ex)
                {
                    return null;
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="SqlComm"></param>
        /// <returns></returns>
        public virtual System.Data.DataTable GetDataTableBySqlComm(string SqlComm)
        {
            if (SqlComm == null || SqlComm == string.Empty)
            {
                return null;
            }
            else
            {
                try
                {
                    SqlComm = iTop > 0 ? SqlComm.ToLower().Replace("select", "select top " + iTop.ToString()) : SqlComm;
                    string order = this.Order == "" || this.Order == null ? "" : " Order by " + this.Order;
                    order = order == "" ? " " : order;
                    if (order.Trim() != "")
                    {
                        order = order.ToLower().Contains("desc") || order.ToLower().Contains("asc") ? order : order + " " + (this.Desc == "Yes" ? " Desc " : " Asc");
                    }
                        FL.SPL.ORM.ObjectMapper om = new FL.SPL.ORM.ObjectMapper(SqlComm);
                    om.SqlComm = SqlComm + " " + order;
                    return om.GetDataBySqlComm();
                }
                catch (System.Exception ex)
                {
                    return null;
                }
            }
        }

        public virtual IList<BaseEntity> GetEntitysByCondition(string Condition)
        {
            FL.SPL.Factory.DialectFactory df = FL.SPL.Factory.Dialects.GetDialect(entity);
            return GetEntitysBySqlComm(df.SelectAllCommand() + " where " + Condition);
        }


        public virtual IList<BaseEntity> GetEntitysBySqlComm(string SqlComm)
        {
            if (SqlComm == null || SqlComm == string.Empty)
            {
                return null;
            }
            else
            {
                try
                {
                    SqlComm = iTop > 0 ? SqlComm.ToLower().Replace("select", "select top " + iTop.ToString()) : SqlComm;
                    string order = this.Order == "" || this.Order == null ? "" : " Order by " + this.Order;
                    order = order == "" ? " " : order;
                    if (order.Trim() != "")
                    {
                        order = order.ToLower().Contains("desc") || order.ToLower().Contains("asc") ? order : order + " " + (this.Desc == "Yes" ? " Desc " : " Asc");
                    }
                    FL.SPL.ORM.ObjectMapper om = new SPL.ORM.ObjectMapper(this.entity);
                    om.SqlComm = SqlComm + " " + order;
                    return om.DatatableToObject();
                }
                catch (System.Exception ex)
                {
                    return null;
                }
            }
        }

        /// <summary>
        /// 条件
        /// </summary>
        //public string Condition
        //{
        //    get;
        //    set;
        //}
        /// <summary>
        /// 分页
        /// </summary>
        /// <returns></returns>
        public virtual IList<BaseEntity> GetEntitysSplitPage(string Condition)
        {
            this.Order = (this.Order == "" ? this.entity.getKey() : this.Order);
                string SqlComm=string.Empty;
                try
                {   
                    string order = string.IsNullOrEmpty(this.Order) ? "" : "( Order by " + this.Order + "  ";
                    if (!order.Contains(",") && !order.ToLower().Contains("desc") && !order.ToLower().Contains("asc"))
                    {
                        order = string.IsNullOrEmpty(order) ? "" : order + (this.Desc == "Yes" ? " Desc) " : " Asc) ");
                    }
                    if (order == "")
                    {
                        order = "(order by id desc) ";
                    }
                    if (!order.Contains(")"))
                    {
                        order = order + ") ";
                    }
                    //string order = string.IsNullOrEmpty(this.Order) ?"" : "( Order by " + this.Order +" ";
                    //order = string.IsNullOrEmpty(order) ? " " : order + (this.Desc == "Yes" ? " Desc) " : " Asc) ");
                    SqlComm = "SELECT TOP "+PageSize.ToString()+" * FROM  (  SELECT ROW_NUMBER() OVER"+order+" AS RowNumber,* FROM " +this.entity.getTableName()+ (string.IsNullOrEmpty(Condition)?"":" where "+Condition)+") A WHERE RowNumber > "+(PageIndex-1)*PageSize+" order by RowNumber";
                    //SqlComm = iTop > 0 ? SqlComm.ToLower().Replace("select", "select top " + PageSize.ToString()) : SqlComm;
                    FL.SPL.ORM.ObjectMapper om = new SPL.ORM.ObjectMapper(this.entity);
                    om.SqlComm = SqlComm;
                    return om.DatatableToObject();
                }
                catch (System.Exception ex)
                {
                    return null;
                }

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="Condition"></param>
        /// <returns></returns>
        public virtual System.Data.DataTable GetDataTableSplitPage(string sql,string Condition)
        {
            this.Order = (this.Order == "" ? this.entity.getKey() : this.Order);
            string SqlComm = string.Empty;
            try
            {
                string order = string.IsNullOrEmpty(this.Order) ? "" : "( Order by " + this.Order + "  ";
                if (!order.Contains(",") && !order.ToLower().Contains("desc") && !order.ToLower().Contains("asc"))
                {
                    order = string.IsNullOrEmpty(order) ? "" : order + (this.Desc == "Yes" ? " Desc) " : " Asc) ");
                }
                if (order == "")
                {
                    order = "(order by id desc) ";
                }
                if (!order.Contains(")"))
                {
                    order = order + ") ";
                }
                SqlComm = "SELECT TOP " + PageSize.ToString() + " * FROM  (SELECT ROW_NUMBER() OVER" + order + " AS RowNumber,* FROM (" + sql + ") as target_table" + (string.IsNullOrEmpty(Condition) ? "" : " where " + Condition) + ") A WHERE RowNumber > " + (PageIndex - 1) * PageSize + " order by rowNumber";
                //SqlComm = iTop > 0 ? SqlComm.ToLower().Replace("select", "select top " + PageSize.ToString()) : SqlComm;
                FL.SPL.ORM.ObjectMapper om = new SPL.ORM.ObjectMapper(this.entity);
                om.SqlComm = SqlComm;
                return om.GetDataBySqlComm();
            }
            catch (System.Exception ex)
            {
                return null;
            }
        }

        public virtual System.Data.DataTable GetDataTableSplitPage(string Condition)
        {
            this.Order = (this.Order == "" ? this.entity.getKey() : this.Order);
            string SqlComm = string.Empty;
            try
            {
                string order = string.IsNullOrEmpty(this.Order) ? "" : "( Order by " + this.Order + "  ";
                if (!order.Contains(",") && !order.ToLower().Contains("desc") && !order.ToLower().Contains("asc"))
                {
                    order = string.IsNullOrEmpty(order) ? "" : order + (this.Desc == "Yes" ? " Desc) " : " Asc) ");
                }
                if (order == "")
                {
                    order = "(order by id desc) ";
                }
                if (!order.Contains(")"))
                {
                    order = order + ") ";
                }
                SqlComm = "SELECT TOP " + PageSize.ToString() + " * FROM  (  SELECT ROW_NUMBER() OVER" + order + " AS RowNumber,* FROM " + this.entity.getTableName() + (string.IsNullOrEmpty(Condition) ? "" : " where " + Condition) + ") A WHERE RowNumber > " + (PageIndex - 1) * PageSize + " order by rowNumber"; 
                //SqlComm = iTop > 0 ? SqlComm.ToLower().Replace("select", "select top " + PageSize.ToString()) : SqlComm;
                FL.SPL.ORM.ObjectMapper om = new SPL.ORM.ObjectMapper(this.entity);
                om.SqlComm = SqlComm;
                return om.GetDataBySqlComm();
            }
            catch (System.Exception ex)
            {
                return null;
            }
        }

        public virtual System.Data.DataTable GetDTByTable(string tableName)
        {
            FL.SPL.ORM.ObjectMapper om = new SPL.ORM.ObjectMapper(null);
            return om.GetDataTableByTableName(tableName);
            //FL.SPL.ORM.ObjectMapper om = new SPL.ORM.ObjectMapper(this.entity);
            //return om.GetDataBySqlComm();
        }

        public virtual System.Data.DataTable GetDTStuceByTable(string tableName)
        {
            FL.SPL.ORM.ObjectMapper om = new SPL.ORM.ObjectMapper(null);
            return om.GetDTStrucByTableName(tableName);
        }



        /// <summary>
        /// 执行 Sql Command
        /// </summary>
        /// <param name="SqlCommand"></param>
        /// <returns></returns>
        public int RunSqlCommand(string SqlCommand)
        {
            return (new FL.DAL.DbSql()).RunSqlCommand(SqlCommand);
        }

        public int GetRowCount(string Condition)
        {
           return (new FL.DAL.DbSql()).GetRowCount(this.entity.GetTableName(), Condition);
        }
        public int GetRowCount(string sql,string Condition)
        {
            return (new FL.DAL.DbSql()).GetSqlRowCount(sql, Condition);
        }

        public BaseEntity GetSum(string[] fieldArrary,string Condition)
        {
            string _FieldStr="";
            foreach (var field in fieldArrary)
            {
                if (_FieldStr == "")
                {
                    _FieldStr = "sum(" + field + ") as " + field;
                }
                else
                {
                    _FieldStr = ",sum(" + field + ") as " + field;
                }
            }
            IList<BaseEntity> list = GetEntitysBySqlComm("select " + _FieldStr + " from " + this.entity.getTableName() + " where " + Condition);
            return list[0];
        }
   
        #endregion


        #region 相关属性
        public virtual int iTop
        {
            get;
            set;
        }

        public virtual string Order
        {
            get;
            set;
        }

        public virtual string Desc
        {
            get;
            set;
        }

        public virtual int PageIndex
        {
            get;
            set;
        }

        public virtual int PageSize
        {
            get;
            set;
        }
        #endregion

    }
}
